package com.example.mall_springboot_01.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.mall_springboot_01.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> res = new HashMap<>();
        String token = request.getHeader("token");
        try{
            DecodedJWT verify = JWTUtils.verify(token);
            return true;//放行
        }catch (SignatureVerificationException e){
            e.printStackTrace();
//            res.put("status",301);
            res.put("msg","签名无效。");
        }catch (TokenExpiredException e){
            e.printStackTrace();
//            res.put("status",302);
            res.put("msg","token过期。");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
//            res.put("status",303);
            res.put("msg","token算法不一致。");
        }catch(Exception e){
            e.printStackTrace();
//            res.put("status",304);
            res.put("msg","token无效。");
        }
        res.put("status",false);
        String json = new ObjectMapper().writeValueAsString(res);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
